<?php
/**
 * Created by PhpStorm.
 * User: zouhua
 * Date: 2018/4/10
 * Time: 14:44
 */

namespace app\controllers;


use app\components\BaseController;
use app\helpers\AppHelper;
use app\models\Categories;
use app\models\Eyny;
use app\models\Post;
use app\models\PostMeta;
use Yii;
use yii\db\Exception;
use yii\web\HttpException;
use yii\web\Response;

class ApiController extends BaseController {

    public $enableCsrfValidation = FALSE;

    public function actionIndex() {
        return time();
    }

    public function actionPostSave() {
        $params = $this->getParam();

        $model = Post::findOne(['slug' => $this->getParam('slug')]);
        if (!$model) {
            $model = new Post();
        }

        $category = Categories::findOne(['title' => $this->getParam('c')]);
        if (!$category) {
            return $this->error();
        }

        $model->cid = $category->id;
        $model->type = $category->type;

        if (!$model->load($params, '')) {
            return $this->error($params);
        }
        return $model->save();
    }

    public function actionCategorySave() {
        $model = Categories::findOne(['title' => $this->getParam('title')]);
        if (!$model) {
            $model = new Categories();
        }
        $model->load($this->post(), '');
        return $model->save();
    }

    public function actionPostMeta() {
        $title = $this->getParam('title');
        $metas = $this->getParam('metas');
        $type = intval($this->getParam('type'));
        $post = Post::find()->where(['slug' => $title])->asArray()->one();
        if (!$post) {
            return $this->error($title);
        }
        if (!is_array($metas) || empty($metas)) {
            return $this->error('metas empty');
        }

        foreach ($metas as $meta) {
            if (PostMeta::find()->where(['post_id' => $post['id'], 'name' => $meta])->one()) {
                continue;
            }
            $model = new PostMeta();
            $model->type = $type;
            $model->post_id = $post['id'];
            $model->name = $meta;
            $model->save();
        }
        return $this->success();
    }


    public function renderException($exception) {
        if (Yii::$app->has('response')) {
            $response = Yii::$app->getResponse();
        } else {
            $response = new Response();
        }

        $code = http_response_code();
        if ($exception instanceof HttpException) {
            $code = $exception->statusCode;
        }
        if ($exception instanceof Exception) {
            $code = AppHelper::ERROR_CODE;
        }

        $data = !YII_ENV_PROD ? ['line' => $exception->getLine(), 'file' => $exception->getFile()] : NULL;
        $response->format = Response::FORMAT_JSON;
        $response->data = AppHelper::error($exception->getMessage(), $code, $data);
        $response->send();
    }
}